package cn.xlbweb.cli.common.exception;

import cn.xlbweb.cli.common.ResponseCode;
import cn.xlbweb.cli.common.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author: bobi
 * @date: 2019-02-04 00:55
 * @description:
 */
@RestControllerAdvice
@Slf4j
public class CliExceptionHandler {

    /**
     * 用户无权限
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = {AuthorizationException.class})
    public ServerResponse authorizationException(Exception e) {
        return ServerResponse.error(ResponseCode.UN_AUTH.getCode(), ResponseCode.UN_AUTH.getMessage());
    }

    /**
     * 账号不存在
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = {UnknownAccountException.class})
    public ServerResponse unknownAccountException(Exception e) {
        return ServerResponse.error(ResponseCode.UNKNOWN_ACCOUNT.getCode(), ResponseCode.UNKNOWN_ACCOUNT.getMessage());
    }

    /**
     * 密码不正确
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = {IncorrectCredentialsException.class})
    public ServerResponse incorrectCredentialsException(Exception e) {
        return ServerResponse.error(ResponseCode.INCORRECT_CREDENTIALS.getCode(), ResponseCode.INCORRECT_CREDENTIALS.getMessage());
    }

    /**
     * 账号被禁用
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = {DisabledAccountException.class})
    public ServerResponse disabledAccountException(Exception e) {
        return ServerResponse.error(ResponseCode.DISABLED_ACCOUNT.getCode(), ResponseCode.DISABLED_ACCOUNT.getMessage());
    }

    /**
     * 登录错误次数过多
     *
     * @return
     */
    @ExceptionHandler(value = {ExcessiveAttemptsException.class})
    public ServerResponse excessiveAttemptsException() {
        return ServerResponse.error(ResponseCode.LOGIN_FAILED_TOO_MUCH.getCode(), ResponseCode.LOGIN_FAILED_TOO_MUCH.getMessage());
    }

    /**
     * 参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = {BindException.class})
    public ServerResponse bindException(BindException e) {
        FieldError fieldError = e.getFieldError();
        String defaultMessage = fieldError.getDefaultMessage();
        log.info("{},原因:{}", ResponseCode.PARAM_VALID_FAILED.getMessage(), defaultMessage);
        return ServerResponse.error(ResponseCode.PARAM_VALID_FAILED.getCode(), defaultMessage);
    }
}
